.text
.section .rodata
.align 8
.LC0:
    .string "Enter a number (empty line to quit):"
.LC1:
    .string "base 10 input, base 10 output: %ld, stopped at %s(% d)\n "
.LC2:
    .string "base 16 input, base 10 output: %ld, stopped at %s(% d)\n "
.LC3:
    .string "Next number:"
.LC4:
    .string "Bye!"

.text
.globl main
.type main, @function
main:
    pushq %rbp
    movq %rsp, %rbp

    subq $48, %rsp
    // 分配一下局部变量
    // number: -30(%rbp)
    // end: -38(%rbp)
    // value: -42(%rbp)

    leaq .LC0(%rip), %rdi
    call puts

    jmp .WHILE_12_COMPARE
.WHILE_12_ENTER:
    leaq -30(%rbp), %rdi
    leaq -38(%rbp), %rsi
    // 10进制
    movl $10, %edx 
    call strtol
    movl %eax, -42(%rbp) /* value */
    movl -42(%rbp) /* value */, %esi
    movq -38(%rbp) /* end */, %rdx
    movb (%rdx), %cl
    movzbl %cl, %ecx
    leaq .LC1(%rip), %rdi
    call printf

    leaq -30(%rbp), %rdi
    leaq -38(%rbp), %rsi
    // 16进制
    movl $16, %edx 
    call strtol
    movl %eax, -42(%rbp) /* value */
    movl -42(%rbp) /* value */, %esi
    movq -38(%rbp) /* end */, %rdx
    movb (%rdx), %cl
    movzbl %cl, %ecx
    leaq .LC2(%rip), %rdi
    call printf

    leaq .LC3(%rip), %rdi
    call puts
.WHILE_12_INCR:
    // 这里不需要做任何事
.WHILE_12_COMPARE:
    leaq -30(%rbp), %rdi
    movl $30 /* LIM */, %esi
    call s_gets
    cmpq $0, %rax
    je .WHILE_12_END
    leaq -30(%rbp), %rax
    movb (%rax), %al
    cmpb $0, %al
    je .WHILE_12_END
    jmp .WHILE_12_ENTER

.WHILE_12_END:

    leaq .LC4(%rip), %rdi
    call puts
    movl $0, %eax
    movq %rbp, %rsp
    popq %rbp
    ret

.globl s_gets
.type s_gets, @function
s_gets:
    pushq %rbp
    movq %rsp, %rbp

    // 得琢磨一下减多少
    // sizeof(st) + sizeof(n) + sizeof(ret_val) + sizeof(i) = 8 + 4 + 8 + 4 = 24
    subq $32, %rsp

    // 分配局部变量
    // st: -8(%rbp)
    // n: -12(%rbp)
    // ret_val: -20(%rbp)
    // i: -24(%rbp)
    movq %rdi, -8(%rbp) /* st */
    movl %esi, -12(%rbp) /* n */
    movl $0, -24(%rbp) /* i */
    // 这两句实际是没必要的
    movq -8(%rbp) /* st */, %rdi
    movl -12(%rbp) /* n */, %esi
    movq stdin(%rip), %rdx
    call fgets
    movq %rax, -20(%rbp) /* ret_val */

    cmpq $0, %rax
    je .EXIT
    jmp .WHILE_15_COMPARE
.WHILE_15_ENTER:
    incl -24(%rbp) /* i */
.WHILE_15_COMPARE:
    movq -8(%rbp) /* st */, %rdi
    movl -24(%rbp) /* i */, %eax
    cltq
    movb (%rdi, %rax, 1), %al
    cmpb $10, %al
    je .WHILE_15_BREAK
    cmpb $0, %al
    je .WHILE_15_BREAK
    jmp .WHILE_15_ENTER
.WHILE_15_BREAK:
    movq -8(%rbp) /* st */, %rdi
    movl -24(%rbp) /* i */, %eax
    cltq
    movb (%rdi, %rax, 1), %al
    cmpb $10, %al
    jne .WHILE_20_COMPARE
    movl -24(%rbp) /* i */, %eax
    cltq
    movb $0, (%rdi, %rax, 1)
    jmp .EXIT

.WHILE_20_COMPARE:
    call getchar
    cmpb $10, %al
    jne .WHILE_20_COMPARE
.EXIT:
    movq -20(%rbp) /* ret_val */, %rax
    movq %rbp, %rsp
    popq %rbp
    ret